let app = getApp()
var stylecss = require('../../utils/stylecss.js');
var checkbox=[];
var checkbox_i=[];
var upload_picture_list=[];
Component({
    properties: {
      scrollTop: {
        type: Number,
        observer: function(newVal, oldVal) {
          this.updatscroll()
        }
      },
      item: {
        type:Object,
        observer: function(newVal, oldVal) {
          this.updateRate()
        }
      }
      },
      data:{
        file_img:'',
        file_more_show:true,
        curr_index:0
      },
    lifetimes: {
      ready: function() {
        let that = this;
        const query = wx.createSelectorQuery().in(this)
        setTimeout(() => { 
           query.select('#'+this.data.item.id).boundingClientRect(res=>{
                that.setData({
                  top:res.top
                })
              }).exec();
         }, 0);
       },
        attached: function () {
       }
      },
    methods: {
      updatscroll:function(){
        var nowtop=this.data.scrollTop-this.data.top
        var oldanima=this.data.oldanima
        if(nowtop<=0){
         this.setData({
           anima:oldanima
         })
        }else{
          this.setData({
              anima:''
          })
        }
     },
      selectchoose:function(e){
          this.setData({
            curr_index:e.currentTarget.dataset.index
          })
      },
      id_cardchange:function(e){
        if(typeof(e.detail.value)!='undefined')
        {
          var form_setting=this.data.list
          form_setting[e.currentTarget.dataset.index]['default_value']=e.detail.value
          form_setting[e.currentTarget.dataset.index]['value']=e.detail.value
          this.setData({
            list:form_setting
          })
          this.triggerEvent('messagelist',form_setting)
        }
      },
      phonechange:function(e){
        if(typeof(e.detail.value)!='undefined')
        {
          var form_setting=this.data.list
          form_setting[e.currentTarget.dataset.index]['default_value']=e.detail.value
          form_setting[e.currentTarget.dataset.index]['value']=e.detail.value
          this.setData({
            list:form_setting
          })
          this.triggerEvent('messagelist',form_setting)
        }
      },
      changeselect:function(e){
            var form_setting=this.data.list
            form_setting[this.data.curr_index]['default_value']=e.detail
            form_setting[this.data.curr_index]['value']=e.detail
            this.setData({
              initValue:e.detail,
              list:form_setting
            })
            this.triggerEvent('messagelist',form_setting)
      },
      suretime:function(){
        var t =this.data.value;
        var year =this.data.years[t[0]];
        var month =this.data.months[t[1]]; 
        var day =this.data.days[t[2]]; 
        var date_value =year + "-" + month + "-" + day;
        var form_setting=this.data.list
        var curr_index=this.data.curr_index
        if(form_setting[curr_index]['type']=='date'){
          form_setting[curr_index]['date_value']=date_value
          form_setting[curr_index]['value']=date_value
        }
        if(form_setting[curr_index]['type']=='datetime'){
          var hour = this.data.hours[t[3]];
          var min =this.data.mins[t[4]];
          var sec =this.data.secs[t[5]];
          var date_timevalue = " " + hour + ":" + min + ":" + sec;
          form_setting[curr_index]['date_value']=date_value+date_timevalue
          form_setting[curr_index]['value']=date_value+date_timevalue
        }
        this.setData({
          list:form_setting,
          visible:false
        })
        this.triggerEvent('messagelist',form_setting)
      },
      dateChange:function(e){
        var t = e.detail.value;
        var form_setting=this.data.list
        var curr_index=this.data.curr_index
        if(form_setting[curr_index]['type']=='date'){
          var value = [t[0],t[1],t[2]];
        }
        if(form_setting[curr_index]['type']=='datetime'){
          var value = [t[0],t[1],t[2],,t[3],t[4],t[5]];
        }
        this.setData({
          value:value
        })
      },
      open_dateTime:function(){
        var t = new Date();
        this.data.year = t.getFullYear(), 
        this.data.month = t.getMonth() + 1, 
        this.data.day = t.getDate(), 
        this.data.hour = t.getHours(), 
        this.data.min = t.getMinutes(), 
        this.data.sec = t.getSeconds();
        var years=[];
        var choose_year=9999;
        for (var o = 2000; o <= t.getFullYear() + 2; o++){
          years.push(o);
          if(o==t.getFullYear()){
            choose_year=o-2000;
          }
        } 
        var value = [choose_year, this.data.month - 1, this.data.day - 1, this.data.hour, this.data.min, this.data.sec ];
        var months=[];
        for (var n = 1; n <= 12; n++){
            months.push(n);
        } 
        var days=[];
        for (var i = 1; i <= 31; i++){
          days.push(i);
        } 
        var hours=[];
        for (var r = 0; r <= 23; r++){
          hours.push(r);
        }
        var mins=[];
        for (var s = 0; s <= 59; s++){
          mins.push(s);
        }
        var secs=[];
        for (var a = 0; a <= 59; a++){
          secs.push(a);
        }
        this.setData({
          years:years,
          months:months,
          hours:hours,
          mins:mins,
          secs:secs,
          days:days,
          visible:true,
          value:value
        })
      },
      open_date:function(){
        var t = new Date();
        this.data.year = t.getFullYear(), 
        this.data.month = t.getMonth() + 1, 
        this.data.day = t.getDate(), 
        this.data.hour = t.getHours(), 
        this.data.min = t.getMinutes(), 
        this.data.sec = t.getSeconds();
        var years=[];
        var choose_year=9999;
        for (var o = 2000; o <= t.getFullYear() + 2; o++){
          years.push(o);
          if(o==t.getFullYear()){
            choose_year=o-2000;
          }
        } 
        var value = [choose_year, this.data.month - 1, this.data.day - 1 ];
        var months=[];
        for (var n = 1; n <= 12; n++){
            months.push(n);
        }
        var days=[];
        for (var i = 1; i <= 31; i++){
          days.push(i);
        } 
        var hours=[];
        var mins=[];
        var secs=[];
        this.setData({
          years:years,
          months:months,
          hours:hours,
          mins:mins,
          secs:secs,
          days:days,
          visible:true,
          value:value
        })
      },
      choosedate:function(e){
        var that = this;
        var index=e.currentTarget.dataset.index
        this.setData({
          curr_index:index
        })
        this.open_date();
      },
      choosedatetime:function(e){
        var that = this;
        var index=e.currentTarget.dataset.index
        this.setData({
          curr_index:index
        })
        this.open_dateTime();
      },
      upfilemore:function(e){
        var that = this;
        var index=e.currentTarget.dataset.index
        var count=e.currentTarget.dataset.count
        wx.showActionSheet({
        itemList: ['从相册中选择', '拍照'],
        success: function (res) {
        if (!res.cancel) {
        if (res.tapIndex == 0) {
               that.choosemoreWxImageShop('album',index,count);
        } else if (res.tapIndex == 1) {
               that.choosemoreWxImageShop('camera',index,count);
            }
          }
         }
      })
      },
      choosemoreWxImageShop: function (type,index,count) {
        var that = this;
        wx.chooseImage({
        sizeType: ['original', 'compressed'],
        sourceType: [type],
        success: function (res) {
        that.upload_morefile(res.tempFilePaths[0],index,count)
           }
         })
        },
        upload_morefile: function (filePath,index,count) {
          var that = this;
          var form_setting=this.data.list
          wx.uploadFile({
          url:app.globalData.siteroot+'&do=Index_uploadFile',
          filePath: filePath,
          name: 'file_upload',
          header: {
          'content-type': 'multipart/form-data'
          }, 
          formData: {
          'do':'Index_uploadFile',
          },
          success: function (res) {
          var data=JSON.parse(res.data)
          upload_picture_list.push(data.info.url)
          if(upload_picture_list.length==count){
            that.setData({
              file_more_show:false
            })
          }
          form_setting[index]['default_value']=upload_picture_list
          form_setting[index]['value']=upload_picture_list
          that.setData({
            list:form_setting,
            upload_picture_list:upload_picture_list
          });
          that.triggerEvent('messagelist',form_setting)
          },
          fail: function (res) {}
          })
      },
        upload_file: function (filePath,index) {
          var that = this;
          var form_setting=this.data.list
          wx.uploadFile({
          url:app.globalData.siteroot+'&do=Index_uploadFile',
          filePath: filePath,
          name: 'file_upload',
          header: {
          'content-type': 'multipart/form-data'
          }, 
          formData: {
          'do':'Index_uploadFile',
          },
          success: function (res) {
          var data=JSON.parse(res.data)
          var  upload_picture=[];
          upload_picture.push(data.info.url)
          form_setting[index]['default_value']=upload_picture
          form_setting[index]['value']=upload_picture
          that.setData({
            file_img:data.info.url,
            list:form_setting
          });
          that.triggerEvent('messagelist',form_setting)
          },
          fail: function (res) {}
          })
      },
      canceluploadmore:function(e){
        var index=e.currentTarget.dataset.index
        var moreindex=e.currentTarget.dataset.moreindex
        console.log(moreindex)
        upload_picture_list.splice(moreindex,1);
        var form_setting=this.data.list
        form_setting[index]['default_value']=upload_picture_list
        form_setting[index]['value']=upload_picture_list
        this.setData({
          upload_picture_list:upload_picture_list,
          file_img:'',
          list:form_setting
        })
        this.triggerEvent('messagelist',form_setting)
      },
      cancelupload:function(e){
        var index=e.currentTarget.dataset.index
        var form_setting=this.data.list
        form_setting[index]['default_value']=[]
        form_setting[index]['value']=[]
        this.setData({
          file_img:'',
          list:form_setting
        })
        this.triggerEvent('messagelist',form_setting)
      },
      upfile:function(e){
        var that = this;
        var index=e.currentTarget.dataset.index
        wx.showActionSheet({
        itemList: ['从相册中选择', '拍照'],
        success: function (res) {
        if (!res.cancel) {
        if (res.tapIndex == 0) {
               that.chooseWxImageShop('album',index);
        } else if (res.tapIndex == 1) {
               that.chooseWxImageShop('camera',index);
            }
          }
         }
      })
      },
      chooseWxImageShop: function (type,index) {
        var that = this;
        wx.chooseImage({
        sizeType: ['original', 'compressed'],
        sourceType: [type],
        success: function (res) {
        that.upload_file(res.tempFilePaths[0],index)
           }
         })
        },
      
      updateRate:function(){
        var list=this.data.item.list[0].values;
        var form_id=this.data.item.list[0].id;
        var css=stylecss.css(this.data.item.id);
        var form_set=this.data.item.id+' .form_set';
        var form_set_btn=this.data.item.id+' .form_set_btn';
        var form_set_css=stylecss.css(form_set);
        var form_set_btn_css=stylecss.css(form_set_btn);
        for(var i=0;i<list.length; i++){
             if(list[i]['type']=='file'&&list[i]['count']>1){
               this.setData({
                upload_picture_list:list[i]['value']
               })
             }
             if(list[i]['type']=='file'&&list[i]['count']==1&&typeof(list[i]['value'])=='undefined'){
              list[i]['default_value']=''
              list[i]['value']=''
              this.setData({
                list:list
              })
            }
        }
        var anima=stylecss.animated(this.data.item.id);
        this.setData({
          oldanima:anima,
          anima:anima,
          form_id:form_id,
          list:list,
          css:css,
          form_set_css:form_set_css,
          form_set_btn_css:form_set_btn_css
        })
      },
      verification:function(){ 
        var form_setting=this.data.list
        for(var i=0;i<form_setting.length; i++){
          if(form_setting[i]['required']==1&&form_setting[i]['show']==1){
            if(typeof(form_setting[i]['value'])=='undefined'||form_setting[i]['value']==''){
              if(form_setting[i]['type']=='text'||form_setting[i]['type']=='textarea'||form_setting[i]['type']=='phone'||form_setting[i]['type']=='id_card'||form_setting[i]['type']=='car_number'){
                wx.showToast({
                  title:'请输入'+form_setting[i]['name'],
                  icon: 'none',
                  duration: 1500
                })
                return false
              }
              if(form_setting[i]['type']=='radio'||form_setting[i]['type']=='checkbox'){
                wx.showToast({
                  title:'请选择'+form_setting[i]['name'],
                  icon: 'none',
                  duration: 1500
                })
                return false
              }
              if(form_setting[i]['type']=='file'){
                wx.showToast({
                  title:'请上传文件',
                  icon: 'none',
                  duration: 1500
                })
                return false
              }
              if(form_setting[i]['type']=='date'){
                wx.showToast({
                  title:'请选择日期',
                  icon: 'none',
                  duration: 1500
                })
                return false
              }
              if(form_setting[i]['type']=='datetime'){
                wx.showToast({
                  title:'请选择时间',
                  icon: 'none',
                  duration: 1500
                })
                return false
              }
              if(form_setting[i]['type']=='select'){
                form_setting[i]['default_value']=form_setting[i]['options'][0]['op_name']
                form_setting[i]['value']=form_setting[i]['options'][0]['op_name']
                var handlerItem= {
                  css: {},
                  nosubmit:true,
                  list: [ {
                      values:form_setting
                  } ]
                }
                this.setData({
                  handlerItem:handlerItem,
                  form_setting:form_setting
                })
              }
            }
            if(form_setting[i]['type']=='phone'){
              var myreg=/^1\d{10}$/
               if (!myreg.test(form_setting[i]['value'])) {
                 wx.showToast({
                   title: '请输入正确'+form_setting[i]['name'],
                   icon: 'none',
                   duration: 1500
                 })
                 return false
               }
             }
             if(form_setting[i]['type']=='id_card'){
              var myreg = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
               if (!myreg.test(form_setting[i]['value'])) {
                 wx.showToast({
                   title:"请输入正确的身份证号",
                   icon: 'none',
                   duration: 1500
                 })
                 return false
               }
             }  
          }
        }
        return true;
       
     },
      submit:function(){
        var that=this
        if(this.verification()){
          wx.request({
            url: app.globalData.siteroot,
            data: {
              do:'Form_formSubmit',
              form_value:that.data.list,
              form_id:that.data.form_id,
              user_id:wx.getStorageSync('user_id')
            },
            success: function(res) {
              wx.showModal({
                content: "表单提交成功！"
              });
            }
          })
        }
      },
      checkboxchange:function(e){
        var form_setting=this.data.list
        var index=e.currentTarget.dataset.index
        var i=e.currentTarget.dataset.i
        var opname=e.currentTarget.dataset.opname
        if(form_setting[index]['options'][i].checked){
          form_setting[index]['options'][i].checked=false
          checkbox.splice(i, 1)
          checkbox_i.splice(i, 1)
        }else{
          form_setting[index]['options'][i].checked=true
          checkbox.push(opname)
          checkbox_i.push(i)
        }
        form_setting[e.currentTarget.dataset.index]['default_value']=checkbox_i
        form_setting[e.currentTarget.dataset.index]['value']=checkbox
        this.setData({
          list:form_setting
        })
        this.triggerEvent('messagelist',form_setting)
      },
      radiochange:function(e){
          var form_setting=this.data.list
          var index=e.currentTarget.dataset.index
          var i=e.currentTarget.dataset.i
          var opname=e.currentTarget.dataset.opname
          var options=form_setting[index]['options']
          for(var p=0;p<options.length; p++){
            form_setting[index]['options'][p].checked=false
          }
          form_setting[index]['options'][i].checked=true
          form_setting[e.currentTarget.dataset.index]['default_value']=i
          form_setting[e.currentTarget.dataset.index]['value']=opname
          this.setData({
            list:form_setting
          })
          this.triggerEvent('messagelist',form_setting)
      },
      valuechange:function(e){
        if(typeof(e.detail.value)!='undefined')
        {
          var form_setting=this.data.list
          form_setting[e.currentTarget.dataset.index]['default_value']=e.detail.value
          form_setting[e.currentTarget.dataset.index]['value']=e.detail.value
          this.setData({
            list:form_setting
          })
          this.triggerEvent('messagelist',form_setting)
        }
      }
    }
});
